package cn.com.scitc.licenseplateback.InterceptorConfiguration.intercepors;

import cn.com.scitc.licenseplateback.absExcetion.TokenException;
import cn.com.scitc.licenseplateback.absExcetion.TokenInvalidation;
import cn.com.scitc.licenseplateback.redis.RedisUtil;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisUtil redisUtil;

    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("cubelibrarytoken");
        if (StringUtils.isBlank(token)) {
            throw new TokenException();
        }

        boolean b = redisUtil.hadKey(token);
        
        if (!b) {
            throw new TokenInvalidation();
        }

        //在用户进行的请求当中，判断用户是否为活跃状态
        //若用户在进行一次请求时，查测到用户登录过期时间不足10分钟
        //且当前用户仍有操作请求，则进行登录延时
        long expire = redisUtil.getExpire(token);
        if (expire <= 600){
            redisUtil.expire(token, expire+1800);
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
